import re
import template
import common
import json


def swagger2py(body: dict, api_dir, test_dir):
    for tag in body['tags']:
        head = 'import json\nimport settings\n\n\n'
        content = ''

        test_head = 'import pytest\n\n\n'
        head_content = ''

        item_list = []
        for (k, v) in body['paths'].items():
            for l in v.values():
                if tag['name'] in l['tags']:
                    item_list.append(k)

        for item_name in item_list:
            tag['name'].replace(' ', '')
            if re.search(r'[\u4e00-\u9fa5]', tag['name']):
                tag['name'] = common.trans_str(tag['name'])[:-2].replace(
                    ' ', '')
            for method in body['paths'][item_name]:
                fun_name = item_name.replace("/",
                                             "_").replace("{",
                                                          "").replace("}", "")
                if fun_name[0] == '_':
                    fun_name = fun_name[1:]
                params = get_api_param(body['paths'][item_name][method])
                if 'description' in body['paths'][item_name][method]:
                    description = body['paths'][item_name][method][
                        'description']
                else:
                    description = ''
                url = item_name
                headers = get_api_header(body['paths'][item_name][method])
                fun_method = method
                content += template.template(fun_name, params, description,
                                             url, headers, fun_method)
                head_content += template.case_template(tag['name'], fun_name,
                                                       params, description,
                                                       api_dir)
        common.generate_file(api_dir, tag['name'], head + content)
        if test_dir:
            common.generate_file(test_dir, 'test_' + tag['name'],
                                 test_head + head_content)


def get_swagger(path):
    with open(path, 'r', encoding='UTF-8') as postman_f:
        result_dict = json.load(postman_f)
        return result_dict


def get_api_param(item):
    if 'parameters' in item:
        return list(item['parameters'])
    else:
        return []


def get_api_header(item):
    result = {}
    if 'consumes' in item:
        result.setdefault("Content-Type", item['consumes'][0])
    return result
